﻿#include "MusicPlayer.h"
#include<qevent.h>
#include"TopWidget.h"
#include"LeftWidget.h"
#include<qfile.h>
#include"MusicEngine.h"
#include<qmediaplayer.h>
#include<qaudiooutput.h>
#include"SearchList.h"
#include"KuGouMusicManager.h"
#include"KuGouApiSource1.h"

MusicPlayer::MusicPlayer(QWidget* parent)
    : QMainWindow(parent), m_isMoveableArea(false)
    ,m_player(new MusicEngine(this))
    ,m_listManager(PlaylistManager::getInstance()),
    m_searchList (new SearchList(this)),
    m_onlineMusicManager(new KuGouMusicManager(std::make_unique<KuGouApiSource1>(), this))
{

    //setWindowOpacity(0.1);
    ui.setupUi(this);
    //ui.widget->show();
    initAll();


    m_listManager.musicFromLocal_Async();
    
    //this->setMouseTracking(true); // 开启当前控件的鼠标追踪

    //已经在desinger中开启
    //ui.widget_2->setMouseTracking(1);
    
#ifdef QT_DEBUG
    //onlineMusicTest();
#endif // QT_DEBUG
    

    connect(m_player, &MusicEngine::errorOccurred, this, 
        [this](QMediaPlayer::Error error, const QString& errorString) {
        qDebug() << "Player Error Code: " << error;
        qDebug() << "Player Error String: " << errorString; // Qt 6.2+
        // qDebug() << "Player Error String: " << m_player->errorString(); // Older Qt 6 / Qt 5
        });
    
    connect(m_player, &MusicEngine::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status) {
        qDebug() << "Media Status: " << status;
        if (status == QMediaPlayer::InvalidMedia) {
            qDebug() << "Error: Invalid media. Source:" << m_player->source();
        }
        });

    connect(m_player, &MusicEngine::playbackStateChanged, this, [this](QMediaPlayer::PlaybackState state) {
        qDebug() << "For URL" << m_player->source().toString() << "Playback State is:" << state;
        });
    connect(m_player, &MusicEngine::durationChanged, this, [this](qint64 duration) {
        qDebug() << "Duration changed for" << m_player->source().toString() << ". New duration:" << duration;
        });

    //KuGouManagerTest();
    //downloadSongTest();
}

MusicPlayer::~MusicPlayer()
{}

//改变光标形状
void MusicPlayer::region(const QPoint& currentGlobalPoint)
{
    constexpr int PADDING = 10; // 建议在类中定义常量或使用 enum

    QRect windowRect = this->rect();
    QPoint leftTop = this->mapToGlobal(windowRect.topLeft());
    QPoint rightBottom = this->mapToGlobal(windowRect.bottomRight());

    int x_mouse = currentGlobalPoint.x();
    int y_mouse = currentGlobalPoint.y();

    // 左上角
    if ((x_mouse >= leftTop.x() && x_mouse <= leftTop.x() + PADDING) &&
        (y_mouse >= leftTop.y() && y_mouse <= leftTop.y() + PADDING)) {
        m_dir = Direction::LEFTTOP;
        this->setCursor(Qt::SizeFDiagCursor);
    }
    // 右下角
    else if ((x_mouse >= rightBottom.x() - PADDING && x_mouse <= rightBottom.x()) &&
        (y_mouse >= rightBottom.y() - PADDING && y_mouse <= rightBottom.y())) {
        m_dir = Direction::RIGHTBOTTOM;
        this->setCursor(Qt::SizeFDiagCursor);
    }
    // 左下角
    else if ((x_mouse >= leftTop.x() && x_mouse <= leftTop.x() + PADDING) &&
        (y_mouse >= rightBottom.y() - PADDING && y_mouse <= rightBottom.y())) {
        m_dir = Direction::LEFTBOTTOM;
        this->setCursor(Qt::SizeBDiagCursor);
    }
    // 右上角
    else if ((x_mouse >= rightBottom.x() - PADDING && x_mouse <= rightBottom.x()) &&
        (y_mouse >= leftTop.y() && y_mouse <= leftTop.y() + PADDING)) {
        m_dir = Direction::RIGHTTOP;
        this->setCursor(Qt::SizeBDiagCursor);
    }
    // 左边
    else if ((x_mouse >= leftTop.x() && x_mouse <= leftTop.x() + PADDING)) {
        m_dir = Direction::LEFT;
        this->setCursor(Qt::SizeHorCursor);
    }
    // 右边
    else if ((x_mouse >= rightBottom.x() - PADDING && x_mouse <= rightBottom.x())) {
        m_dir = Direction::RIGHT;
        this->setCursor(Qt::SizeHorCursor);
    }
    // 上边
    else if ((y_mouse >= leftTop.y() && y_mouse <= leftTop.y() + PADDING)) {
        m_dir = Direction::UP;
        this->setCursor(Qt::SizeVerCursor);
    }
    // 下边
    else if ((y_mouse >= rightBottom.y() - PADDING && y_mouse <= rightBottom.y())) {
        m_dir = Direction::DOWN;
        this->setCursor(Qt::SizeVerCursor);
    }
    // 非边角区域
    else {
        m_dir = Direction::NONE;
       
        this->setCursor(Qt::ArrowCursor);
    }
}

QPoint MusicPlayer::getMousePos(const QPoint& prevGlobal, const QPoint& nowGlobal)
{
    return nowGlobal - prevGlobal;
}

void MusicPlayer::changeEvent(QEvent* ev)
{
    auto windowState = this->windowState();
    //是窗口改变事件
    if (ev->type() == QEvent::WindowStateChange) {
        if (windowState == Qt::WindowNoState) {
            ui.titleBar->setBtnMaxNormalIcon();
        }
        else if (windowState == Qt::WindowMaximized) {
            ui.titleBar->setBtnMaxIcon();
        }
    }
    QMainWindow::changeEvent(ev);
}

void MusicPlayer::mouseDoubleClickEvent(QMouseEvent* ev)
{
    if (ev->buttons() & Qt::LeftButton) {
        if (ui.titleBar->rect().contains(ev->pos()))
        {
            switch (this->windowState())
            {
            case Qt::WindowMaximized:
                this->setWindowState(Qt::WindowNoState);
                break;
            case Qt::WindowNoState:
                this->setWindowState(Qt::WindowMaximized);
                break;
            default:
                break;
            }
        }
    }
    QMainWindow::mouseDoubleClickEvent(ev);
}

void MusicPlayer::resizeEvent(QResizeEvent* event)
{
    QMainWindow::resizeEvent(event);

    //QPalette pal = this->palette();
    //QPixmap pixmap(":/icons/background(1).png");
    //// 获取当前窗口的逻辑尺寸
    //QSize currentSize = this->size();
    //// 缩放图片至当前尺寸
    //QPixmap scaledPix = pixmap.scaled(currentSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    //pal.setBrush(QPalette::Window, QBrush(scaledPix));
    //this->setPalette(pal);
}

#ifdef QT_DEBUG
#include"KuGouApi.h"
#include"KuGouApiSource1.h"
#include<qnetworkaccessmanager.h>
#include<qnetworkreply.h>
#include<qnetworkrequest.h>
#include"KuGouMusicManager.h"
#include"JsonKeysConfig.h"
#include"MusicList.h"
void MusicPlayer::onlineMusicTest()
{
 

    connect(ui.titleBar, &TopWidget::searchFinished, this,
        [this](QString message) {
            qDebug() << "message is " << message;
            KuGouApi* api = new KuGouApiSource1;    //内存泄漏
            QNetworkAccessManager* manager = new QNetworkAccessManager(this);
            QNetworkRequest request(api->searchSongs(message));
            //QNetworkRequest request(QUrl("http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword=相信自己&page=1&pagesize=20&showtype=1"));
            QNetworkReply* reply =  manager->get(request);
            connect(reply, &QNetworkReply::finished, 
                [reply] {
                    QByteArray data =  reply->readAll();
                    qDebug() << QString::fromUtf8(data);
                });
        });
}

void MusicPlayer::KuGouManagerTest() {
    m_onlineMusicManager = new KuGouMusicManager(std::make_unique<KuGouApiSource1>(), this);
    QStringList parent;
    parent << "data" << "info";
    OnlionMusicInfo info;
    
    info.duration_s = "duration";
    info.payType = "pay_type";
    info.songExtname = "extname";
    info.singerName = "singername";
    info.songHash = "hash";
    info.songName = "songname";
    JsonKeysConfig jsonConfig(parent,std::move(info));

    m_onlineMusicManager->searchSong(jsonConfig,"长歌一曲");
    //connect(m_onlineMusicManager, &KuGouMusicManager::searchMusicFinished,
    //    [this](QList<OnlionMusicInfo> infos) {
    //        for (auto& i : infos)
    //        {
    //            qDebug() << i;
    //        }
    //    });
}

void MusicPlayer::downloadSongTest() {
    QUrl url("https://sharefs.tx.kugou.com/202506211655/7eb736348fbc71f430064cd48d5eb674/v3/e1f7aeea7553fb0eed589f15fcdd99f1/yp/full/ap1000_us0_pi409_s1455080627.mp3");
    QString singerName = "";
    QString songName = "越来越不懂";

    m_onlineMusicManager = new KuGouMusicManager(std::make_unique<KuGouApiSource1>(), this);
    m_onlineMusicManager->downloadSong(url, singerName, songName);
}

void MusicPlayer::initMusicList() {
    
    m_musicList = new MusicList;
    int index = ui.pages->addTab(m_musicList, "MusicList");
    connect(m_musicList, &MusicList::doubleClicked,
        [this](QUrl url) {
            m_player->play(url);
        });

    connect(&m_listManager, qOverload<const QList<Song>&>(&PlaylistManager::songsScannedBatch),
        [this](const QList<Song>& list) {
            m_musicList->appendSong(list);
        });
    //ui.pages->setCornerWidget(nullptr);
    //m_musicList->setStyleSheet("background-color: red;");
    //QVBoxLayout* layout = new QVBoxLayout(ui.pages->widget(index));
    //layout->addWidget(m_musicList);
}
#endif

void MusicPlayer::mousePressEvent(QMouseEvent* ev)
{

    QMainWindow::mousePressEvent(ev);
}

void MusicPlayer::mouseMoveEvent(QMouseEvent* ev)
{
   
    QMainWindow::mouseMoveEvent(ev);

}

void MusicPlayer::mouseReleaseEvent(QMouseEvent* ev)
{
    
    //m_isLeftPressDown = false;

    
    QMainWindow::mouseReleaseEvent(ev);
}

void MusicPlayer::initTitleBar()
{
    connect(ui.titleBar, &TopWidget::closePlayer, [this]() {
        this->close();
        });
    connect(ui.titleBar, &TopWidget::minimizePlayer, [this]() {
        this->showMinimized();
        });
    connect(ui.titleBar, &TopWidget::maximizePlayer, [this]() {
        if (this->windowState() == Qt::WindowNoState) {
            m_normalWindowGlobalRect = this->rect();
            this->showMaximized();
        }
        else {
            this->showNormal();
        }
        });
}

void MusicPlayer::initLeftWidgets()
{
    // 不要用 addItem("文本")，而是手动 new 一个 QListWidgetItem
    LeftWidget* item1 = new LeftWidget(QIcon(":icons/zhanweifu.png"), "123");
    // 设置项的尺寸，让它能容下你的自定义 widget
    //QListWidgetItem* it1 = new QListWidgetItem;
    //it1->setSizeHint(QSize(50,50));
    //ui.leftWidgets->addItem(it1);
    //ui.leftWidgets->setItemWidget(it1, item1);

    LeftWidget* item2 = new LeftWidget(QIcon(":icons/zhanweifu.png"), "播放列表");
    QListWidgetItem* it2 = new QListWidgetItem; 
    ui.leftWidgets->addItem(it2);
    it2->setSizeHint(QSize(50, 50));
    ui.leftWidgets->setItemWidget(it2, item2);

    LeftWidget* item3 = new LeftWidget(QIcon(":icons/zhanweifu.png"), "搜索列表");
    QListWidgetItem* it3 = new QListWidgetItem;
    ui.leftWidgets->addItem(it3);
    it3->setSizeHint(QSize(50, 50));
    ui.leftWidgets->setItemWidget(it3, item3);
    
    
    connect(ui.leftWidgets, &QListWidget::itemClicked,
        [this](QListWidgetItem* item) {
            int row = ui.leftWidgets->row(item);
            ui.pages->setCurrentIndex(row);
        });

}

void MusicPlayer::initStyleSheet(const QString& fileName)
{
    QFile file(fileName);
    if (file.open(QFile::ReadOnly)) {
        QString qss = QString::fromUtf8(file.readAll());
        this->setStyleSheet(qss);
        file.close();
    }
    
}

void MusicPlayer::initBackground()
{

    QPalette pal = this->palette(); 
    QPixmap pixmap(":/icons/background(1).png");
    QPixmap  scalPix = pixmap.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    pal.setBrush(QPalette::Window, QBrush(scalPix));
    this->setPalette(pal);
 

}

//void MusicPlayer::initSongList()
//{
//    //设置表头属性
//    ui.musicList->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
//    ui.musicList->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
//    //ui.musicList->horizontalHeader()->setVisible(false);
//    //列宽
//    ui.musicList->horizontalHeader()->setStretchLastSection(true);
//    ui.musicList->setColumnWidth(0, 350);
//    ui.musicList->setColumnWidth(1, 100);
//    //ui.musicList->setColumnWidth(2, 500);
//    
//    //关闭表格线
//    ui.musicList->setShowGrid(false);
//    
//    ui.musicList->setSelectionBehavior(QAbstractItemView::SelectRows);
//    ui.musicList->setSelectionMode(QAbstractItemView::SingleSelection);
//    ui.musicList->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    //ui.musicList->setFocusPolicy(Qt::NoFocus);
//    //ui.musicList->setStyleSheet(
//    //    "QTableWidget::item:selected:focus {"
//    //    "    border: none;"                  // 移除选中项的焦点边框
//    //    "}");
//    //ui.musicList->setStyleSheet(
//    //    "QTableWidget::item {"
//    //    "    border: none; /* 移除所有单元格的边框 */"
//    //    "}"
//    //    "QTableWidget::item:selected {"
//    //    //"    background-color: blue; /* 设置选中背景颜色 */"
//    //    "    color: white; /* 设置选中文本颜色 */"
//    //    "    border: none; /* 移除选中时的边框 */"
//    //    "}"
//    //    "QTableWidget::item:selected:focus {"
//    //    "    border: none; /* 移除焦点状态下的边框 */"
//    //    "}");
////    ui.musicList->setStyleSheet(
////R"(QTableWidget{
////	outline:none;
////}
////QTableWidget::item:selected:focus{
////	background-color:#0078d7;
////}
////QTableWidget::item:!selected:focus{
////	background-color:transparent;
////}
////QTableWidget::item:hover{
////    backgournd-color:rgb(240, 243, 250);
////    border: 1px solid #0078d7;
////}
////)");
//
//    ui.musicList->setStyleSheet(
//        R"(QTableWidget{
//    outline:none;
//}
//QTableWidget::item:selected{
//    background-color:#0078d7;  /* 保持选中项背景色 */
//    color: white;  /* 保持选中文本的颜色 */
//}
//QTableWidget::item:!selected{
//    background-color:transparent;  /* 非选中项的背景色 */
//}
//QTableWidget::item:hover{
//    background-color:rgb(240, 243, 250);
//    border: 1px solid #0078d7;
//}
//)");
//}

void MusicPlayer::initPlayer()
{

    m_player->setVolume(15);
       

    //播放按钮改变状态
    connect(ui.bottomBar, &BottomBar::btnPlayMusic, 
        [this](bool clicked) {
            
            auto state = m_player->playbackState();
            //qDebug() << "播放列表长度 = " << SongList::getInstance().size();
            
            qDebug() << "playbackState = " << state;
            QMediaMetaData data = m_player->metaData();
            qDebug() << "时长 = " << data.value(data.Duration).toInt();
            if (state == QMediaPlayer::PlayingState) {
                m_player->pause();
            }
            else if(state == QMediaPlayer::PausedState
                || state == QMediaPlayer::StoppedState)
            {
                m_player->play();
                m_musicList->helightRow(0);
            }
        });

    //上一首按钮
    connect(ui.bottomBar, &BottomBar::btnPrevMusic
        , [this](bool clicked) {
            m_player->play(m_musicList->prevMusic());
        });

    //下一首按钮
    connect(ui.bottomBar, &BottomBar::btnNextMusic
        , [this](bool clicked) {
            m_player->play(m_musicList->nextMusic());
        });
    
    //自动播放
    connect(m_player, &MusicEngine::mediaStatusChanged,
        [this](QMediaPlayer::MediaStatus status) {

            if (status == QMediaPlayer::EndOfMedia)
            {
                qDebug() << "source is " << m_player->source();
                if (m_musicList->playMode() == MusicList::PlayMode::RepeatSingle)
                {
                    
                    m_player->play();
                }
                else
                {
                    m_player->play(m_musicList->nextMusic());
                }
                qDebug() << "source is " << m_player->source();
            }
        });


    //状态改变图标
    connect(m_player, &MusicEngine::playbackStateChanged,
        [this](QMediaPlayer::PlaybackState newState) {
            if (newState == QMediaPlayer::StoppedState
                || newState == QMediaPlayer::PausedState) {
                ui.bottomBar->setPlayIcon();
            }
            else if (newState == QMediaPlayer::PlayingState) {
                ui.bottomBar->setPauseIcon();
            }
        });
}

//void MusicPlayer::initTableWidget()
//{
//    //auto& list = m_listManager.getList();
//    auto curList = m_listManager.getCurSongList();
//    /*ui.musicList->setRowCount(5);*/
//    ui.musicList->setColumnCount(2);
//    //插入信息
//    connect(&m_listManager, qOverload<int>( & PlaylistManager::songsScannedBatch), this,
//        [this,curList](int beginPos) {
//            int size = (*curList).size();
//            qDebug() << "PlaylistManager::songsScannedBatch信号已接收";
//            qDebug() << "list.size() = " << (*curList).size();
//            ui.musicList->setRowCount(size - beginPos);
//            for (int i = 0; i < size; i++)
//            {
//                QTableWidgetItem* item1 = new QTableWidgetItem((*curList)[i].songName);
//                ui.musicList->setItem(i,0,item1);
//                QTableWidgetItem* item2 = new QTableWidgetItem((*curList)[i].duration_s);
//                ui.musicList->setItem(i, 1, item2);
//            }
//            qDebug() << "PlaylistManager::songsScannedBatch信号已接收";
//        }
//    );
//
//    connect(m_player, &MusicEngine::getCurIndex, 
//        [this](int rowIndex) {
//            qDebug() << "current row is" << rowIndex;
//            ui.musicList->selectRow(rowIndex);
//        });
//
//    //双击播放
//    connect(ui.musicList,&QTableWidget::itemDoubleClicked,
//        [this](QTableWidgetItem* item) {
//            m_player->play(item->row());
//            m_player->setCurIndex(item->row());
//        });
//
//
//
//}

void MusicPlayer::initBottomBar()
{
    //按住滑块，放下时改变值
    connect(ui.bottomBar, &BottomBar::sliderReleasedValue, this,
        [this](int val) {
            m_player->setPosition(val);
        });

    connect(m_player, &MusicEngine::positionChanged, this,
        [this](qint64 pos) {
            if (ui.bottomBar->isSliderDown() == false) {
                ui.bottomBar->setSliderValue(pos);
            }
            
        });

    connect(m_player, &MusicEngine::durationChanged, this, 
        [this](qint64 duration_ms) {
            ui.bottomBar->setSliderRange(0, duration_ms);
        });
}

void MusicPlayer::initSearchList()
{
    ui.pages->addTab(m_searchList,"searchList");
    QStringList parent;
    parent << "data" << "info";
    OnlionMusicInfo info;

    info.duration_s = "duration";
    info.payType = "pay_type";
    info.songExtname = "extName";
    info.singerName = "singername";
    info.songHash = "hash";
    info.songName = "songname";
    JsonKeysConfig config(parent, info);
    m_onlineMusicManager->setJsonKeysConfig(config);

    OnlionMusicInfo keysInfo(info);
    keysInfo.duration_s = "timeLength";
    keysInfo.url = "url";
    JsonKeysConfig urlConfig(QStringList(), keysInfo);

    //搜索框发送
    connect(ui.titleBar, &TopWidget::searchFinished, this,
        [this,config,urlConfig](const QString& message) {
            m_onlineMusicManager->searchSong(config,urlConfig,message);
            ui.pages->setCurrentWidget(m_searchList);
            qDebug() << "搜索成功";
        });

    //添加出url外的信息
    connect(m_onlineMusicManager, &KuGouMusicManager::searchFinished,
        [this](const QList<OnlionMusicInfo>& infos) {

            m_searchList->appendSong(infos);
            qDebug() << "添加成功";
        });

    connect(m_onlineMusicManager, qOverload<QList<QUrl>>(&KuGouMusicManager::getUrl),
        [this](const QList<QUrl>& urlList) {
            m_searchList->scrollTop();
            m_searchList->appendUrl(urlList);
        });

    connect(m_searchList, &SearchList::mouseLeftDoubleClicked,
        [this](const Song& s) {
            qDebug() << "url: ";
            if (!s.url.isEmpty())
            {
                m_musicList->push_front(s);
                m_musicList->helightRow(0);
                m_player->play(s.url);                
            }
            
        });


}

void MusicPlayer::initAll()
{
    // 去掉标题栏,去掉在Windows状态栏的显示，窗口置顶
    setWindowFlags(Qt::FramelessWindowHint /*| Qt::Tool*/ /*| Qt::WindowStaysOnTopHint*/);
    this->setMinimumSize(1060, 720);
    enableMouseTrackingRecursively(this);
    initTitleBar();
    initLeftWidgets();
    //initBackground();
    //initSongList();
    initPlayer();
    //initTableWidget();
    initBottomBar();
    
    initStyleSheet("MusicPlayer.qss");

#ifdef QT_DEBUG
    initMusicList();
    initSearchList();
#endif // QT_DEBUG
    
}


void MusicPlayer::enableMouseTrackingRecursively(QWidget* widget)
{
    static int count = 0;
    if (!widget) return;

    widget->setMouseTracking(true);
    widget->installEventFilter(this);  // 安装事件过滤器
    const QObjectList& children = widget->children();
    for (QObject* child : children) {
        QWidget* childWidget = qobject_cast<QWidget*>(child);
        if (childWidget) {
            enableMouseTrackingRecursively(childWidget);
        }
    }
}


/*
解决方案：
A. 在事件过滤器中处理各种拖放、缩放操作，把TopWidget中按钮的mouseTrack关闭
B(个人倾向). 重写mousePressed、mosueMoveEvent、mouseReleaseEvent，然后逃离当子控件包含鼠标时，改变光标形状
*/
bool MusicPlayer::eventFilter(QObject* obj, QEvent* event)
{
    auto type = event->type();
    if (type == QEvent::MouseButtonPress) {
        QMouseEvent* ev = static_cast<QMouseEvent*>(event);
        if (ev->buttons() & Qt::LeftButton) {
            const auto mouse = this->mapFromGlobal(ev->globalPosition().toPoint());
            //qDebug() << mouse;
            if (ui.titleBar->rect().contains(mouse))
            {
                m_isMoveableArea = true;
            }
            else
            {
                m_isMoveableArea = false;
            }
            switch (ev->button())
            {
            case Qt::LeftButton:
                //m_isLeftPressDown = true;
                m_relativePosPressed_Mouse_Window = ev->pos();//m_mousePressedGlobalPoint - mapToGlobal(this->rect().topLeft());

                /*if (m_dir == NONE) {*/
                    // ? 
                this->m_mousePressedGlobalPoint = ev->globalPosition().toPoint();
                //}
                //else
                //{
                //    this->mouseGrabber();
                //}
            case Qt::RightButton:
                //m_isLeftPressDown = false;

            default:

                break;
            }

        }
    }
    else if (type == QEvent::MouseMove) {
        QMouseEvent* ev = static_cast<QMouseEvent*>(event);

        QPoint mouseMovingGlobalPoint = ev->globalPosition().toPoint();   //移动时鼠标全局坐标

        QRect rect = this->rect();  //rect == QRect(0,0 1280x720)
        QPoint topLeft = mapToGlobal(rect.topLeft());
        QPoint bottomRight = mapToGlobal(rect.bottomRight());
        
        //改变光标形状
        if (this->windowState() != Qt::WindowMaximized) {
            //如果没有最大化

            // 显示光标
            if (ev->buttons() == Qt::NoButton)
            {
                region(mouseMovingGlobalPoint);
            }
            /*else*/ if (ev->buttons() & Qt::LeftButton)
            {

                if (m_dir != Direction::NONE) {
                    QRect newWindow(topLeft, bottomRight);
                    QPoint mousesRelativePos = getMousePos(m_mousePressedGlobalPoint, mouseMovingGlobalPoint);
                    switch (m_dir)
                    {
                    case Direction::UP:
                        //上
                        if (bottomRight.y() - mouseMovingGlobalPoint.y() >= this->minimumHeight()) {
                            newWindow.setTop(mouseMovingGlobalPoint.y());
                        }

                        break;
                    case Direction::DOWN:
                        //下
                        if (mouseMovingGlobalPoint.y() - topLeft.y() >= this->minimumHeight()) {
                            newWindow.setBottom(mouseMovingGlobalPoint.y());
                        }

                        break;
                    case Direction::LEFT:
                        //左
                        if (bottomRight.x() - mouseMovingGlobalPoint.x() >= this->minimumWidth()) {
                            newWindow.setLeft(mouseMovingGlobalPoint.x());
                        }

                        break;
                    case Direction::RIGHT:
                        //右
                        if (mouseMovingGlobalPoint.x() - topLeft.x() >= this->minimumWidth()) {
                            newWindow.setRight(mouseMovingGlobalPoint.x());
                        }

                        break;
                    case Direction::LEFTTOP:
                        //newWindow.setTopLeft(mouseMovingGlobalPoint);
                        //左上
                        if ((bottomRight.x() - mouseMovingGlobalPoint.x() >= this->minimumWidth()
                            && bottomRight.y() - mouseMovingGlobalPoint.y() >= this->minimumHeight()))
                        {
                            newWindow.setLeft(mouseMovingGlobalPoint.x());
                            newWindow.setTop(mouseMovingGlobalPoint.y());
                        }
                        //左
                        else if (bottomRight.x() - mouseMovingGlobalPoint.x() >= this->minimumWidth()) {
                            newWindow.setLeft(mouseMovingGlobalPoint.x());
                        }
                        //上
                        else if (bottomRight.y() - mouseMovingGlobalPoint.y() >= this->minimumHeight()) {
                            newWindow.setTop(mouseMovingGlobalPoint.y());
                        }

                        break;
                    case Direction::LEFTBOTTOM:
                        //newWindow.setBottomLeft(mouseMovingGlobalPoint);
                        //左下
                        if ((bottomRight.x() - mouseMovingGlobalPoint.x() >= this->minimumWidth())
                            && (mouseMovingGlobalPoint.y() - topLeft.y() >= this->minimumHeight()))
                        {
                            newWindow.setLeft(mouseMovingGlobalPoint.x());
                            newWindow.setBottom(mouseMovingGlobalPoint.y());
                        }
                        //左
                        else if (bottomRight.x() - mouseMovingGlobalPoint.x() >= this->minimumWidth()) {
                            newWindow.setLeft(mouseMovingGlobalPoint.x());
                        }
                        //下
                        else if (mouseMovingGlobalPoint.y() - topLeft.y() >= this->minimumHeight()) {
                            newWindow.setBottom(mouseMovingGlobalPoint.y());
                        }
                        break;
                    case Direction::RIGHTBOTTOM:
                        //右下
                        if ((mouseMovingGlobalPoint.x() - topLeft.x() >= this->minimumWidth())
                            && (mouseMovingGlobalPoint.y() - topLeft.y() >= this->minimumHeight())) {
                            newWindow.setRight(mouseMovingGlobalPoint.x());
                            newWindow.setBottom(mouseMovingGlobalPoint.y());
                        }
                        //右
                        else if (mouseMovingGlobalPoint.x() - topLeft.x() >= this->minimumWidth()) {
                            newWindow.setRight(mouseMovingGlobalPoint.x());
                        }
                        //下
                        else if (mouseMovingGlobalPoint.y() - topLeft.y() >= this->minimumHeight()) {
                            newWindow.setBottom(mouseMovingGlobalPoint.y());
                        }
                        //newWindow.setBottomRight(mouseMovingGlobalPoint);
                        break;
                    case Direction::RIGHTTOP:
                        //右上
                        if ((mouseMovingGlobalPoint.x() - topLeft.x() >= this->minimumWidth())
                            && (bottomRight.y() - mouseMovingGlobalPoint.y() >= this->minimumHeight())) {
                            newWindow.setRight(mouseMovingGlobalPoint.x());
                            newWindow.setTop(mouseMovingGlobalPoint.y());
                        }
                        //右
                        else if (mouseMovingGlobalPoint.x() - topLeft.x() >= this->minimumWidth()) {
                            newWindow.setRight(mouseMovingGlobalPoint.x());
                        }
                        //上
                        else if (bottomRight.y() - mouseMovingGlobalPoint.y() >= this->minimumHeight()) {
                            newWindow.setTop(mouseMovingGlobalPoint.y());
                        }
                        //newWindow.setTopRight(mouseMovingGlobalPoint);
                        break;
                    case Direction::NONE:
                        break;
                    default:
                        break;
                    }
                    //qDebug() << "缩放";
                    this->setGeometry(newWindow);
                }
                else
                {

                    if (m_isMoveableArea) {
                        //qDebug() << "移动";
                        this->move(mouseMovingGlobalPoint - m_relativePosPressed_Mouse_Window);
                    }
                }
            }

        }
        //窗口是最大化的
        else {
            if (m_isMoveableArea
                && ev->buttons() & Qt::LeftButton) {

                //this->setWindowState(Qt::WindowState::WindowNoState);
                showNormal();
                //this->move(m_mousePressedGlobalPoint.x() -ev->scenePosition().toPoint().x()
                //    , m_mousePressedGlobalPoint.y());
            }
        }
    }
    else if (type == QEvent::MouseButtonRelease) {
        QMouseEvent* ev = static_cast<QMouseEvent*>(event);
        if (m_dir == Direction::NONE) {
            this->setCursor(Qt::ArrowCursor);
        }
        m_dir = Direction::NONE;
    }
    return QMainWindow::eventFilter(obj, event);
}